<template>
  <view class="coupon-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <text class="header-title">优惠券管理</text>
        <view class="header-actions">
          <uni-icons type="search" size="20" color="#fff" @click="showSearchBar = !showSearchBar" />
          <uni-icons type="settings" size="20" color="#fff" @click="handleSettings" style="margin-left: 16rpx;" />
        </view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section" v-if="showSearchBar">
      <view class="search-bar">
        <uni-easyinput
          prefixIcon="search"
          v-model="queryParams.keyword"
          placeholder="请输入优惠券名称"
          @confirm="handleSearch"
          :inputBorder="false"
          class="search-input"
        ></uni-easyinput>
      </view>
    </view>

    <!-- 数据概览卡片 -->
    <view class="overview-section">
      <view class="overview-card">
        <view class="overview-item">
          <text class="overview-value">{{ overviewData.totalCoupons }}</text>
          <text class="overview-label">优惠券总数</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">{{ overviewData.issuedCount }}</text>
          <text class="overview-label">已发放</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">{{ overviewData.usedCount }}</text>
          <text class="overview-label">已使用</text>
        </view>
      </view>
    </view>

    <!-- 功能模块网格 -->
    <view class="modules-section">
      <view class="modules-grid">
        <view 
          class="module-card" 
          v-for="module in modules" 
          :key="module.key"
          @click="navigateToModule(module)"
        >
          <view class="module-icon">
            <uni-icons :type="module.icon" size="32" :color="module.color" />
          </view>
          <text class="module-title">{{ module.title }}</text>
          <text class="module-desc">{{ module.desc }}</text>
          <view class="module-badge" v-if="module.badge">
            <text class="badge-text">{{ module.badge }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 优惠券类型筛选 -->
    <view class="filter-section">
      <text class="section-title">优惠券类型</text>
      <scroll-view class="filter-scroll" scroll-x>
        <view class="filter-list">
          <view
            v-for="tab in couponTypeTabs"
            :key="tab.value"
            class="filter-item"
            :class="{ active: queryParams.type === tab.value }"
            @click="handleTabChange(tab.value)"
          >
            {{ tab.label }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 优惠券列表 -->
    <view class="list-section">
      <text class="section-title">优惠券列表</text>
      <scroll-view scroll-y class="list-scroll" @scrolltolower="handleScrollToLower">
        <view v-if="!loading && coupons.length === 0" class="empty-container">
          <uni-icons type="folder-opened" size="60" color="#ccc"></uni-icons>
          <text class="empty-text">暂无优惠券</text>
        </view>
        <view v-else class="coupon-list">
          <view v-for="coupon in coupons" :key="coupon.id" class="coupon-card" :class="{ 'batch-mode': batchMode }" @click="handleCouponClick(coupon)">
            <!-- 批量选择复选框 -->
            <view v-if="batchMode" class="batch-checkbox" @click.stop="toggleCouponSelection(coupon.id)">
              <uni-icons 
                :type="selectedCoupons.includes(coupon.id) ? 'checkbox-filled' : 'circle'" 
                size="20" 
                :color="selectedCoupons.includes(coupon.id) ? '#1890FF' : '#ccc'"
              ></uni-icons>
            </view>
            
            <view class="card-content">
              <view class="card-header">
                <view class="coupon-info">
                  <text class="coupon-name">{{ coupon.name }}</text>
                  <text class="coupon-desc">{{ coupon.description || '暂无描述' }}</text>
                </view>
                <view class="coupon-value">
                  <text class="value-text">{{ formatCouponValue(coupon) }}</text>
                  <uni-tag :text="getCouponTypeText(coupon.type)" type="primary" size="small"></uni-tag>
                </view>
              </view>
              
              <view class="card-body">
                <view class="info-row">
                  <view class="info-item">
                    <text class="info-label">使用门槛</text>
                    <text class="info-value">{{ formatMinConsume(coupon) }}</text>
                  </view>
                  <view class="info-item">
                    <text class="info-label">有效期</text>
                    <text class="info-value">{{ coupon.valid_days }}天</text>
                  </view>
                </view>
                <view class="info-row">
                  <view class="info-item">
                    <text class="info-label">库存</text>
                    <text class="info-value">{{ coupon.total_count - coupon.issued_count }}</text>
                  </view>
                  <view class="info-item">
                    <text class="info-label">状态</text>
                    <uni-tag :text="coupon.status ? '启用' : '禁用'" :type="coupon.status ? 'success' : 'error'" size="small"></uni-tag>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <uni-load-more :status="loadMoreStatus"></uni-load-more>
      </scroll-view>
    </view>

    <!-- 批量操作栏 -->
    <view class="batch-actions" v-if="selectedCoupons.length > 0">
      <view class="batch-info">
        <text>已选择 {{ selectedCoupons.length }} 项</text>
      </view>
      <view class="batch-buttons">
        <button class="batch-btn enable-btn" @click="batchEnable" :loading="batchProcessing">
          启用
        </button>
        <button class="batch-btn disable-btn" @click="batchDisable" :loading="batchProcessing">
          禁用
        </button>
        <button class="batch-btn delete-btn" @click="batchDelete" :loading="batchProcessing">
          删除
        </button>
      </view>
    </view>

    <!-- 浮动操作按钮 -->
    <view class="fab-container" v-if="!batchMode">
      <view class="fab-button" @click="goToDetail()">
        <uni-icons type="plus" size="24" color="#fff"></uni-icons>
      </view>
    </view>

    <!-- 批量模式切换按钮 -->
    <view class="batch-toggle" v-if="coupons.length > 0">
      <view class="toggle-button" @click="toggleBatchMode">
        <uni-icons type="checkbox" size="20" color="#1890FF"></uni-icons>
        <text class="toggle-text">{{ batchMode ? '取消选择' : '批量选择' }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { onPullDownRefresh, onReachBottom, onLoad } from '@dcloudio/uni-app';
import { fetchCoupons, batchUpdateCouponStatus, batchDeleteCoupons } from '@/api/coupon';
import { getCouponTypeText, formatCouponValue, formatMinConsume } from '@/utils/coupon';
import { CouponType, ApplicableType } from '@/types/coupon';
import type { Coupon, CouponQuery } from '@/types/coupon';

const coupons = ref<Coupon[]>([]);
const loading = ref(true);
const showSearchBar = ref(false);
const queryParams = reactive<CouponQuery>({
  page: 1,
  pageSize: 10,
  keyword: '',
  type: undefined,
});
const total = ref(0);
const loadMoreStatus = ref('more');

// 数据概览
const overviewData = ref({
  totalCoupons: 0,
  issuedCount: 0,
  usedCount: 0,
});

// 批量操作相关
const batchMode = ref(false);
const selectedCoupons = ref<number[]>([]);
const batchProcessing = ref(false);

// 功能模块配置
const modules = ref([
  {
    key: 'activity',
    title: '活动管理',
    desc: '优惠券活动',
    icon: 'calendar',
    color: '#1890FF',
    path: '/pages/coupons/activity/index',
    badge: '',
  },
  {
    key: 'verify',
    title: '核销管理',
    desc: '券码核销',
    icon: 'scan',
    color: '#52C41A',
    path: '/pages/coupons/verify/index',
    badge: '',
  },
  {
    key: 'statistics',
    title: '数据统计',
    desc: '统计分析',
    icon: 'bars',
    color: '#FA8C16',
    path: '/pages/coupons/statistics/index',
    badge: '',
  },
  {
    key: 'settings',
    title: '设置管理',
    desc: '系统设置',
    icon: 'gear',
    color: '#722ED1',
    path: '/pages/coupons/settings/index',
    badge: '',
  },
]);

const couponTypeTabs = [
  { label: '全部', value: undefined },
  { label: '折扣券', value: CouponType.Discount },
  { label: '现金券', value: CouponType.Cash },
  { label: '满减券', value: CouponType.Reduction },
  { label: '时长券', value: CouponType.Duration },
];

// 加载数据概览
const loadOverviewData = async () => {
  try {
    // 这里应该调用统计API获取概览数据
    overviewData.value = {
      totalCoupons: coupons.value.length,
      issuedCount: coupons.value.reduce((sum, coupon) => sum + coupon.issued_count, 0),
      usedCount: coupons.value.reduce((sum, coupon) => sum + coupon.used_count, 0),
    };
  } catch (error) {
    console.error('加载概览数据失败:', error);
  }
};

const getCoupons = async (isRefresh = false) => {
  if (isRefresh) {
    queryParams.page = 1;
  }
  loadMoreStatus.value = 'loading';
  try {
    const res = await fetchCoupons(queryParams);
    if (isRefresh) {
      coupons.value = res.list;
    } else {
      coupons.value = [...coupons.value, ...res.list];
    }
    total.value = res.total;
    if (coupons.value.length >= total.value) {
      loadMoreStatus.value = 'noMore';
    } else {
      loadMoreStatus.value = 'more';
    }
    
    // 更新概览数据
    await loadOverviewData();
  } catch (error) {
    console.error('获取优惠券列表失败:', error);
    loadMoreStatus.value = 'more';
  } finally {
    loading.value = false;
    uni.stopPullDownRefresh();
  }
};

const handleSearch = () => {
  getCoupons(true);
};

const handleTabChange = (type: CouponType | undefined) => {
  queryParams.type = type;
  getCoupons(true);
};

const handleScrollToLower = () => {
  if (loadMoreStatus.value === 'more') {
    queryParams.page = (queryParams.page || 1) + 1;
    getCoupons();
  }
};

const goToDetail = (id?: number) => {
  const url = id ? `/pages/coupons/detail?id=${id}` : '/pages/coupons/detail';
  uni.navigateTo({ url });
};

const handleCouponClick = (coupon: Coupon) => {
  if (batchMode.value) {
    toggleCouponSelection(coupon.id);
  } else {
    goToDetail(coupon.id);
  }
};

// 导航到模块页面
const navigateToModule = (module: any) => {
  uni.navigateTo({
    url: module.path,
  });
};

// 处理设置
const handleSettings = () => {
  uni.showActionSheet({
    itemList: ['批量选择', '数据导出', '系统设置'],
    success: (res) => {
      switch (res.tapIndex) {
        case 0:
          toggleBatchMode();
          break;
        case 1:
          uni.showToast({
            title: '功能开发中',
            icon: 'none',
          });
          break;
        case 2:
          uni.navigateTo({
            url: '/pages/coupons/settings/index'
          });
          break;
      }
    }
  });
};

// 批量操作方法
const toggleBatchMode = () => {
  batchMode.value = !batchMode.value;
  selectedCoupons.value = [];
};

const toggleCouponSelection = (couponId: number) => {
  const index = selectedCoupons.value.indexOf(couponId);
  if (index > -1) {
    selectedCoupons.value.splice(index, 1);
  } else {
    selectedCoupons.value.push(couponId);
  }
};

const batchEnable = async () => {
  if (selectedCoupons.value.length === 0) return;
  
  uni.showModal({
    title: '确认操作',
    content: `确定要启用选中的 ${selectedCoupons.value.length} 个优惠券吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          batchProcessing.value = true;
          await batchUpdateCouponStatus(selectedCoupons.value, 1);
          
          uni.showToast({
            title: '批量启用成功',
            icon: 'success'
          });
          
          getCoupons(true);
          selectedCoupons.value = [];
        } catch (error) {
          console.error('批量启用失败:', error);
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          });
        } finally {
          batchProcessing.value = false;
        }
      }
    }
  });
};

const batchDisable = async () => {
  if (selectedCoupons.value.length === 0) return;
  
  uni.showModal({
    title: '确认操作',
    content: `确定要禁用选中的 ${selectedCoupons.value.length} 个优惠券吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          batchProcessing.value = true;
          await batchUpdateCouponStatus(selectedCoupons.value, 0);
          
          uni.showToast({
            title: '批量禁用成功',
            icon: 'success'
          });
          
          getCoupons(true);
          selectedCoupons.value = [];
        } catch (error) {
          console.error('批量禁用失败:', error);
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          });
        } finally {
          batchProcessing.value = false;
        }
      }
    }
  });
};

const batchDelete = async () => {
  if (selectedCoupons.value.length === 0) return;
  
  uni.showModal({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedCoupons.value.length} 个优惠券吗？此操作不可恢复！`,
    success: async (res) => {
      if (res.confirm) {
        try {
          batchProcessing.value = true;
          await batchDeleteCoupons(selectedCoupons.value);
          
          uni.showToast({
            title: '批量删除成功',
            icon: 'success'
          });
          
          getCoupons(true);
          selectedCoupons.value = [];
        } catch (error) {
          console.error('批量删除失败:', error);
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        } finally {
          batchProcessing.value = false;
        }
      }
    }
  });
};

onLoad(() => {
  getCoupons(true);
});

onReachBottom(() => {
  handleScrollToLower();
});

// 页面加载
onMounted(() => {
  loadOverviewData();
});

// 注册下拉刷新事件
onPullDownRefresh(() => {
  Promise.all([
    getCoupons(true),
    loadOverviewData(),
  ]).finally(() => {
    uni.stopPullDownRefresh();
  });
});
</script>

<style lang="scss" scoped>
.coupon-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #1890FF 0%, #F0F9FF 30%);
}

.header {
  padding-top: var(--status-bar-height);
  background: linear-gradient(135deg, #1890FF 0%, #40A9FF 100%);
  
  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 32rpx;
    
    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #fff;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
    }
  }
}

.search-section {
  padding: 0 32rpx 16rpx;
  
  .search-bar {
    background: #fff;
    border-radius: 16rpx;
    padding: 8rpx 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    
    .search-input {
      background-color: transparent;
    }
  }
}

.overview-section {
  margin: -20rpx 32rpx 32rpx;
  
  .overview-card {
    display: flex;
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    box-shadow: 0 4rpx 20rpx rgba(24, 144, 255, 0.1);
    
    .overview-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .overview-value {
        font-size: 32rpx;
        font-weight: 600;
        color: #1890FF;
        margin-bottom: 8rpx;
      }
      
      .overview-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.modules-section {
  padding: 0 32rpx 32rpx;
  
  .modules-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24rpx;
    
    .module-card {
      position: relative;
      background: #fff;
      border-radius: 16rpx;
      padding: 32rpx 24rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.1);
      }
      
      .module-icon {
        margin-bottom: 16rpx;
      }
      
      .module-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .module-desc {
        font-size: 24rpx;
        color: #999;
      }
      
      .module-badge {
        position: absolute;
        top: 16rpx;
        right: 16rpx;
        background: #FF4D4F;
        border-radius: 20rpx;
        padding: 4rpx 12rpx;
        
        .badge-text {
          font-size: 20rpx;
          color: #fff;
        }
      }
    }
  }
}

.filter-section, .list-section {
  padding: 0 32rpx 24rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
}

.filter-scroll {
  white-space: nowrap;
  
  .filter-list {
    display: flex;
    gap: 16rpx;
    padding-bottom: 16rpx;
    
    .filter-item {
      flex-shrink: 0;
      background: #fff;
      border-radius: 20rpx;
      padding: 16rpx 32rpx;
      font-size: 24rpx;
      color: #666;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      
      &.active {
        background: #1890FF;
        color: #fff;
        box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.3);
      }
    }
  }
}

.list-scroll {
  max-height: 600rpx;
}

.coupon-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.coupon-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
  
  &.batch-mode {
    padding-left: 60rpx;
  }
  
  .card-content {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 24rpx;
      
      .coupon-info {
        flex: 1;
        
        .coupon-name {
          font-size: 28rpx;
          font-weight: 600;
          color: #333;
          display: block;
          margin-bottom: 8rpx;
        }
        
        .coupon-desc {
          font-size: 24rpx;
          color: #999;
          line-height: 1.4;
        }
      }
      
      .coupon-value {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 8rpx;
        
        .value-text {
          font-size: 32rpx;
          font-weight: 600;
          color: #1890FF;
        }
      }
    }
    
    .card-body {
      .info-row {
        display: flex;
        margin-bottom: 16rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .info-item {
          flex: 1;
          display: flex;
          flex-direction: column;
          
          .info-label {
            font-size: 22rpx;
            color: #999;
            margin-bottom: 4rpx;
          }
          
          .info-value {
            font-size: 24rpx;
            color: #333;
            font-weight: 500;
          }
        }
      }
    }
  }
}

.batch-checkbox {
  position: absolute;
  left: 24rpx;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1;
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  .empty-text {
    margin-top: 24rpx;
    color: #999;
    font-size: 28rpx;
  }
}

.batch-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-top: 1rpx solid #e8e8e8;
  padding: 24rpx 32rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .batch-info {
    flex: 1;
    
    text {
      font-size: 28rpx;
      color: #333;
    }
  }
  
  .batch-buttons {
    display: flex;
    gap: 16rpx;
    
    .batch-btn {
      padding: 12rpx 24rpx;
      border-radius: 8rpx;
      font-size: 24rpx;
      border: none;
      
      &.enable-btn {
        background-color: #52c41a;
        color: #fff;
      }
      
      &.disable-btn {
        background-color: #faad14;
        color: #fff;
      }
      
      &.delete-btn {
        background-color: #ff4d4f;
        color: #fff;
      }
    }
  }
}

.fab-container {
  position: fixed;
  right: 32rpx;
  bottom: 32rpx;
  
  .fab-button {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #1890FF 0%, #40A9FF 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8rpx 24rpx rgba(24, 144, 255, 0.3);
  }
}

.batch-toggle {
  position: fixed;
  right: 32rpx;
  bottom: 160rpx;
  
  .toggle-button {
    background: #fff;
    border-radius: 40rpx;
    padding: 16rpx 24rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
    
    .toggle-text {
      font-size: 24rpx;
      color: #1890FF;
      margin-left: 8rpx;
    }
  }
}
</style>